#!/usr/bin/env python3
"""
测试运行器
运行项目的所有测试用例
"""

import unittest
import sys
import os
from pathlib import Path

def main():
    """运行所有测试"""
    # 设置项目根目录
    project_root = Path(__file__).parent
    
    # 添加项目根目录到Python路径
    sys.path.insert(0, str(project_root))
    
    print("=" * 60)
    print("量化股票数据系统 - 测试套件")
    print("=" * 60)
    
    # 发现并运行测试
    loader = unittest.TestLoader()
    start_dir = project_root / 'tests'
    
    if not start_dir.exists():
        print(f"错误: 测试目录不存在: {start_dir}")
        return 1
    
    # 发现测试用例
    suite = loader.discover(str(start_dir), pattern='test_*.py')
    
    # 运行测试
    runner = unittest.TextTestRunner(verbosity=2, buffer=True)
    result = runner.run(suite)
    
    # 输出结果统计
    print("\n" + "=" * 60)
    print("测试结果统计:")
    print(f"运行测试: {result.testsRun}")
    print(f"失败: {len(result.failures)}")
    print(f"错误: {len(result.errors)}")
    print(f"跳过: {len(result.skipped) if hasattr(result, 'skipped') else 0}")
    
    if result.failures:
        print(f"\n失败的测试:")
        for test, traceback in result.failures:
            print(f"  - {test}")
    
    if result.errors:
        print(f"\n错误的测试:")
        for test, traceback in result.errors:
            print(f"  - {test}")
    
    # 返回退出码
    if result.failures or result.errors:
        print("\n❌ 测试未完全通过")
        return 1
    else:
        print("\n✅ 所有测试通过")
        return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)